//
//  JSEvaluaCell.m
//  jshop
//
//  Created by 张艳江 on 2019/5/22.
//  Copyright © 2019 张艳江. All rights reserved.
//

#import "SCEvaluaCell.h"
#import "UploadImageCell.h"

#define MAX_COUNT 6

@interface SCEvaluaCell()<UICollectionViewDelegate,UICollectionViewDataSource,StarEvaluatorDelegate>

@property (strong, nonatomic) StarEvaluator    *consultStarView;
@property (strong, nonatomic) StarEvaluator    *logisticsStarView;
@property (strong, nonatomic) MessageTextView  *textView;

@property (strong, nonatomic) NSMutableArray      *imagesFiles;
@property (strong, nonatomic) TZImagePickerHelper *helper;
@property (strong, nonatomic) NSMutableArray      *upImagesData;

@end

@implementation SCEvaluaCell

- (TZImagePickerHelper *)helper{
    if (!_helper) {
        _helper = [[TZImagePickerHelper alloc] init];
        WeakSelf;
        dispatch_group_t group = dispatch_group_create();
        
        _helper.finish = ^(NSArray *array, BOOL isEnd){
            
            [SVProgressHUD showWithStatus:@"上传中..."];
            
            [weakSelf.imagesFiles addObjectsFromArray:array];
            
            dispatch_group_enter(group);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                UIImage *image = [UIImage imageWithContentsOfFile:array[0]];
                NSString *url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftAppOrder&a=upload"];
                [[NetworkRequestTool sharedNetworkTool] uploadWithURL:url parameters:nil images:@[image] name:@"file" fileName:nil mimeType:@"image/png" progress:nil success:^(id result, NSString *error) {
                    //NSLog(@"----%@",result);
                    if ([result[@"status"] isEqualToString:@"true"]) {
                        [weakSelf.upImagesData addObject:result[@"data"]];
                        [weakSelf.collectionView reloadData];
                        if (isEnd == YES) {
                            [SVProgressHUD dismiss];
                            weakSelf.model.upPicArray = [weakSelf.upImagesData copy];
                        }
                        dispatch_group_leave(group);
                    }else{
                        [weakSelf.upImagesData removeAllObjects];
                        [SVProgressHUD showImage:nil status:result[@"info"]];
                        dispatch_group_leave(group);
                        return ;
                    }
                } failure:^(NSError *error) {
                    [weakSelf.upImagesData removeAllObjects];
                    [SVProgressHUD showImage:nil status:@"上传失败，请检查您的网络连接"];
                    dispatch_group_leave(group);
                    return ;
                }];
            });
        };
    }
    return _helper;
}
- (NSMutableArray *)imagesFiles{
    if (!_imagesFiles) {
        _imagesFiles = [NSMutableArray array];
    }
    return _imagesFiles;
}
- (NSMutableArray *)upImagesData{
    if (!_upImagesData) {
        _upImagesData = [NSMutableArray array];
    }
    return _upImagesData;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.goodsImage.contentMode = UIViewContentModeScaleAspectFill;
    self.goodsImage.clipsToBounds = YES;
    
    //评价
    self.consultStarView = [[StarEvaluator alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];
    self.consultStarView.tag = 0;
    self.consultStarView.currentValue = 5;
    self.consultStarView.delegate = self;
    [self.starBgView addSubview:self.consultStarView];
    
    //物流评价
    self.logisticsStarView = [[StarEvaluator alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];
    self.logisticsStarView.tag = 1;
    self.logisticsStarView.currentValue = 5;
    self.logisticsStarView.delegate = self;
    [self.logisticsStarBgView addSubview:self.logisticsStarView];
    
    self.textBgView.layer.borderColor = RGB(239, 239, 239).CGColor;
    self.textBgView.layer.borderWidth = 0.7f;
    
    self.textView = [[MessageTextView alloc]initWithFrame:CGRectMake(5, 0, kScreenW - 30, 120) text:@"宝贝满足您的期待吗？说说您的使用心得" isLimit:YES];
    self.textView.limitNum = 130;
    self.textView.backgroundColor = [UIColor clearColor];
    WeakSelf;
    self.textView.endText = ^(NSString *text) {
        weakSelf.model.comment = text;
    };
    [self.textBgView addSubview:self.textView];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumLineSpacing = 8;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;//滚动方向
    
    layout.itemSize = CGSizeMake(80, 80);
    
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    //定义xib文件
    [self.collectionView registerNib:[UINib nibWithNibName:@"UploadImageCell" bundle:nil] forCellWithReuseIdentifier:@"UploadImageCellID"];
}
#pragma mark - 滑动评价代理
- (void)starEvaluator:(StarEvaluator *)evaluator currentValue:(float)value{
    if (evaluator.tag == 0) {//商品评分
        self.starLab.text = [NSString stringWithFormat:@"%.2f",value];
        self.model.score = self.starLab.text;
    }else{
        self.logisticsStarLab.text = [NSString stringWithFormat:@"%.2f",value];
        self.model.deliver_score = self.logisticsStarLab.text;
    }
}
#pragma mark  --------UICollectionVIew 的代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.imagesFiles.count == 5) {
        return self.imagesFiles.count;
    }
    return self.imagesFiles.count + 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UploadImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UploadImageCellID" forIndexPath:indexPath];
    
    if (indexPath.row == self.imagesFiles.count){
        cell.img_pic.image = [UIImage imageNamed:@"shangchuantupian"];
        cell.btn_del.hidden = YES;
    }else{
        cell.img_pic.image = [UIImage imageWithContentsOfFile:self.imagesFiles[indexPath.row]];
        cell.btn_del.hidden = NO;
    }
    cell.img_pic.contentMode =  UIViewContentModeScaleAspectFill;
    
    [cell.btn_del addTarget:self action:@selector(onDelClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.btn_del.tag = indexPath.row;
    
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    [self endEditing:YES];
    if (indexPath.row == self.imagesFiles.count){
        
        if ((MAX_COUNT - self.imagesFiles.count) <= 0) return;
        
        [self.helper showImagePickerControllerWithMaxCount:(MAX_COUNT - self.imagesFiles.count) WithViewController:self.vc];
    }else{
        // preview photos or video / 预览照片或者视频
    }
}
#pragma mark ----删除图片
-(void)onDelClick:(UIButton *)sender{
    [self.imagesFiles removeObjectAtIndex:sender.tag];
    [self.upImagesData removeObjectAtIndex:sender.tag];
    self.model.upPicArray = [self.upImagesData copy];
    [self.collectionView reloadData];
}
#pragma mark - 设置数据
- (void)setModel:(SCModel *)model{
    
    _model = model;
    
    [self.goodsImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",Goods_ImageURL,model.wap_pic]] placeholderImage:[UIImage imageNamed:@""]];
   
    self.goodsTitleLab.text = model.gift_name;
    self.model.score = @"5";
    self.model.deliver_score = @"5";
    self.model.comment = @"";
    self.model.anonymous = @"1";
    self.model.upPicArray = @[];
}
- (IBAction)clickAnonymousBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
        self.model.anonymous = @"0";
    }else{
        self.model.anonymous = @"1";
    }
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}

@end
